/**
 * tournote file;
 * company:junqitecch
 * author:xuzuiotao
 * 发表游迹的用户或者
 * mongodb TourNote{
          {
           _id:
           userID:
           contID:
           type:
           toID:
           text:
           image:
           createTime:
          }
 *  
 *
 */



var mongoClient = require('mongodb').MongoClient;
var consts = require('../consts');
var tournote_user = require('./tournote_user');

/*
 * 获取自增长的timeline和commentid
 */
function getNextComment_Value(db, callback){
	console.log('mmmaaa');
	
	   db.collection('ids').findAndModify(
			   {'_id': 'autoID' },
			   [['_id','asc']],   
			   {$inc:{'tournote_comment_value':1,'timeline_value':1}},
			   {'new':true,upsert:true},
			   callback);
	   
}

/*
 * 根据ids批量获取评论如果db为空则初始化db后调用batchCommentInner函数
 */
function  batchComments(ids,db,callback){

	if(db===null){
		var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
		mongoClient.connect(url,consts.MongoOptions, function(err, dbopen) {  
		    if (err)  
		    {  
		    	var error = new Error();
		    	error.number= consts.Error.ERROR_GENERAL;
		    	error.message=consts.Message.UNKNOWN;
		    	
		        console.log(err);
		        if(callback){
		        	callback(error,null);
		        }
		    }  
		    else  
		    {  
		    	batchCommentInner(ids,db,callback);
		    }  
		});  

	}else{
		batchCommentInner(ids,db,callback);
	}

}

function batchCommentInner(ids,db,callback){
	var col = db.collection("tournote_comment"); 
	console.log(ids);
	col.find({'_id':{$in:ids}}).hint({'baseLine':-1}).toArray(function(err, result){
	    if(err)
	    {
	        console.log('Error:'+ err);
     	  	var error = new Error();

	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	db.close();
	        if(callback){
	        	callback(error,null);
	        }
	        return;
	   }

	   if(callback){
           callback(null,result);
	   }
	  
	});
	
}

/*
 * 获取评论列表的命令，因为要封装成response中的data内容，单独处理，在此单独处理
 */

function listCommentCommand(contID,baseLine,direction,count,callback){

		var url = consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
		mongoClient.connect(url,consts.MongoOptions, function(err, dbopen) {  
		    if (err)  
		    {  
		    	var error = new Error();
		    	error.number= consts.Error.ERROR_GENERAL;
		    	error.message=consts.Message.UNKNOWN;
		    	
		        console.log(err);
		        if(callback){
		        	callback(error,null);
		        }
		    }  
		    else  
		    {
		    	listCommenttoData(contID,baseLine,direction,count,dbopen,null,true,callback);
		    }
		});

}

/*
 * 将获取的评论详情填充到response的data数据中，detail 不为0时候额外添加自己的userID replies 为true 显示回复条目
 */

function listCommenttoData(contID,baseLine,direction,count,db,detail,replies,callback){
	listCommentInner(contID,baseLine,direction,count,db,function(err,result){
		
		if(err){
  	        console.log('Error:'+ err);
  	        var error = new Error();
  	    	error.number= consts.Error.ERROR_GENERAL;
  	    	error.message=consts.Message.UNKNOWN;
  	    	
  	        if(callback){
  	        	callback(error,null);
  	        }
	        db.close();

  	        return;
  	    }
        var  i =0;
 
  	    var first=0;
  	    var last=0;
  	    var count=result.length;
  	    if(result.length>0){
  	        first=result[0].baseLine;
  	        last=result[result.length-1].baseLine;
  	    }
  	    
  	    var userIDs = [];
  	    var dic = [];
  	    var todic=[];
  	    var toIDs = [];
  	    if(detail!==null){
  	    	dic[detail.userID+'']=detail.userID;
  	    }
  	   
  	    for(i=0;i<result.length;i++){
  	    	dic[result[i].userID+'']=result[i].userID;
  	    	if(typeof(result[i].toID)!=='undefined' && result[i].toID!==0 && result[i].toID!==null){
  	    	    todic[result[i].toID+'']= result[i].toID;
  	    	}else{
  	    		
  	    	}
  	    	delete result[i].baseLine;
  	    }
  	    var key =null;
  	    for ( key in dic) {
  	    	userIDs.push(dic[key]);
  	    }
  	    
  	    for ( key in todic) {
  	    	toIDs.push(todic[key]);
  	    	todic[key]=null;
  	    }

  	    if(toIDs.length>0 && replies){
  	    	batchComments(toIDs,db,function(err,list){
  	    		if(list!==null){
	  	    		 for(i=0;i<list.length;i++){
	  	     	    	dic[list[i].userID+'']=list[i].userID;
	  	     	    	delete list[i].baseLine;
	  	     	    	todic[list[i]._id+'']=list[i];
	  	     	    }
	  	    		
	  	    		 for (var key in dic) {
	  	     	    	userIDs.push(dic[key]);
	  	     	    }
  	    		
  	    		}

  	    		
  	    		tournote_user.batchUsers(userIDs,db,function(error,users){
  	    			if(error){
  	    				console.log('Error  aaa   '+error.message);
  	    			}else{
  	    				console.log(JSON.stringify(users));
  	    			}
  	  	  	    	var content= {};
  	  		    	if(first>0)content.first=first;
  	  		    	if(last>0)content.last=last;
  	  		    	if(users !==null){
  	  		    		
	  	  		    	for(i=0; i<users.length;i++){
	  	  		    		dic[users[i].userID+'']=users[i];
	  	  		    	}
  	  		    	}
  	  		    	
  	  		    	if(detail!==null){
  	  		    		detail.user=dic[detail.userID+''];
  	  		    		delete detail.userID;
  	  		    	}
  	  			if(error){
	    				console.log('Error 11 '+error.message);
	    			}else{
	    				console.log(JSON.stringify(users));
	    			}
  	  			
  	  		    	for(i=0;i<result.length;i++){
  	  		    		result[i].user=dic[result[i].userID+''];
  	  		    		delete result[i].userID;
  	  		    		if(typeof(result[i].toID)!='undefined' && 
  	  		    				result[i].toID!==0 && 
  	  		    				result[i].toID!==null&&
  	  		    				todic[result[i].toID+'']!==null){
  	  		    			result[i].replied=todic[result[i].toID+''];  	  		    		
  	  		    		}
  	  		    	}
  	  		    	for(i=0;i<list.length;i++){
  	  		    	list[i].user=dic[list[i].userID+''];
	  		    		delete list[i].userID;  	  	
	  		    		
  	  		    	}
  	  		    	
  	  		    	content.count=count;
  	  		    	if(count>0){
  	  			    	content.comments=result;
  	  		    	}
  	  		    	
	    	        db.close();

  	  		    	if(callback){
  	  			        callback(null,content);
  	  		    	}  	   
  	  	  	    }); 
  	    		
  	    	});
  	    	
  	    	
  	    }else{
  	    	 
  	    	tournote_user.batchUsers(userIDs,db,function(error,users){
  	  	    	var content= {};
  	  	    	if(users){
  	  	    		for(i=0;i<users.length;i++){
  	  	    			dic[users[i].userID+'']=users[i];
  	  	    		}
  	  	    	}
  	  	    	
  		    	if(first>0)content.first=first;
  		    	if(last>0)content.last=last;

  		    	if(detail!==null){
	  		    	detail.user=dic[detail.userID+''];
	  		    	delete detail.userID;
	  		   }
	  		    
  		    	content.count=count;
  		    	if(count>0){
  		    		for(i=0;i<result.length;i++){
  		    			result[i].user=dic[result[i].userID+''];
	  		    		delete result[i].userID;
  		    		}
  			    	content.comments=result;
  		    	}
  		    	if(callback){
  			        callback(null,content);
  		    	}  	   
  	  	    
  	    	});
  	    	
  	    }
  	    
  	   
	});

}

/*
 * 获取评论列表
 */

function listComment(contID,baseLine,direction,count,db,callback){

	if(db===null){
		var url =  consts.MongoURL;// 'mongodb://59.110.54.101:2700/tournote';  
		mongoClient.connect(url,consts.MongoOptions, function(err, dbopen) {  
		    if (err)  
		    {  
		    	var error = new Error();
		    	error.number= consts.Error.ERROR_GENERAL;
		    	error.message=consts.Message.UNKNOWN;
		    	
		        console.log(err);
		        if(callback){
		        	callback(error,null);
		        }
		    }  
		    else  
		    {
				listCommentInner(contID,baseLine,direction,count,dbopen,callback);
		    }
		});
	}else{
		listCommentInner(contID,baseLine,direction,count,db,callback);
	}

}

/*
 * 获取评论列表
 */

function listCommentInner(contID,baseLine,direction,count,db,callback){

	var col = db.collection('tournote_comment'); 
	var whereStr ={'contID':contID};
	if(baseLine!==0){
		if(direction>0){
			whereStr={'contID':contID,'baseLine':{$gt:baseLine}};
		}else{
			whereStr={'contID':contID,'baseLine':{$lt:baseLine}};
		}	
	}

	col.find(whereStr).hint({'baseLine':-1}).limit(count).toArray(function(err, result){
		
	    if(err)
	    {
	        console.log('Error:'+ err);
     	  	var error = new Error();

	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        if(callback){
	        	callback(error,null);
	        }
	        return;
	    }else{
        	callback(null,result);
	    }
	});
	  
}  

/*
 * 添加游迹用户，
 */

function insert(comment,user,db,callback){

	if(db===null){
		var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
		mongoClient.connect(url,consts.MongoOptions, function(err, dbopen) {  
		    if (err)  
		    {  
		    	var error = new Error();
		    	error.number= consts.Error.ERROR_GENERAL;
		    	error.message=consts.Message.UNKNOWN;
		    	
		        console.log(err);
		        if(callback){
		        	callback(error,null);
		        }
		    }  
		    else  
		    {  
		    	upsertCommentInner(comment,user, dbopen,callback);
		    }  
		});  

	}else{
		upsertCommentInner(comment,user, db,callback);
	}

}

function praise(param,user,callback){


	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	var error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var col = db.collection("tournote_praise");
	    	if(param.cancel){
	    		console.log('cancel');
	    		col.remove({'contID':param.contID,'userID':user.userID},function(erro,resu){

		    		  if (erro)  
		    		    {  
		    		    	var error = new Error();
		    		    	error.number= consts.Error.ERROR_GENERAL;
		    		    	error.message=consts.Message.UNKNOWN;
		    		    	
		    		        console.log(err);
		    		        if(callback){
		    		        	callback(error,null);
		    		        }
		    		        return;
		    		    }  
		    		
		    		
		    	     	var colnote = db.collection("tournote");

		    	     	console.log(-resu.result.n);
		    	     	
		    		    colnote.findAndModify({'_id':param.contID},[],{$inc:{'praisedNum':-resu.result.n}},{'new':true,upsert:false},function(e,obj){
		    		    	if(e){
		    		    		var error = new Error();
			    		    	error.number= consts.Error.ERROR_GENERAL;
			    		    	error.message=consts.Message.UNKNOWN;
			    		    	
			    		        console.log(err);
			    		        if(callback){
			    		        	callback(error,null);
			    		        }
				    	        db.close();

			    		        return;
		    		    	}else{
		    		    		var content = {};
		    		    		
		    		    	    content.praised=1;
		    		    		content.praisedNum= obj.value.praisedNum;
		    	    	        db.close();

		    		    		callback(null, content);
		    		    	}
		    		    });
	    		
		    	});
		
	    		
	    	}else{
	    		getNextComment_Value(db,function(err,obj){
	    			var prais = {};
	    			prais._id=obj.value.tournote_comment_value;
			        var t=Date.now();
			               
			        prais.contID=param.contID;
			        prais.userID=user.userID;
			        prais.createTime = t;
			        prais.baseLine=obj.value.timeline_value;
			        col.save(prais,function(erro,resu){

			    		  if (erro)  
			    		    {  
			    		    	error = new Error();
			    		    	error.number= consts.Error.ERROR_GENERAL;
			    		    	error.message=consts.Message.UNKNOWN;
			    		    	
			    		        console.log(erro);
			    		        if(callback){
			    		        	callback(error,null);
			    		        }
				    	        db.close();

			    		        return;
			    		    }  
			    		
			    		
			    	     	var colnote = db.collection("tournote");

			    	     	console.log(-resu.result.n);
			    	     	
			    		    colnote.findAndModify({'_id':param.contID},[],{$inc:{'praisedNum':resu.result.n,'baseLine':obj.value.timeline_value}},{'new':true,upsert:false},function(e,obj){
			    		    	if(e){
			    		    		error = new Error();
				    		    	error.number= consts.Error.ERROR_GENERAL;
				    		    	error.message=consts.Message.UNKNOWN;
				    		    	
				    		        console.log(err);
				    		        if(callback){
				    		        	callback(error,null);
				    		        }
					    	        db.close();

				    		        return;
			    		    	}else{
			    		    		var content = {};
			    		    		content.praisedNum= obj.value.praisedNum;
			    		    	    content.praised=2;
			    	    	        db.close();

			    		    		callback(null, content);
			    		    	}
			    		    });
		    		
			    	});
			

	    		});
	    		
	    		
	    	}
	    	
	    }  
	}); 
}


function commentDel(param,user,callback){

	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	var error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;

	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var col = db.collection("tournote_comment"); 
	        console.log('1111111111');
	        console.log(param);
	    	col.remove({'contID':param.contID,'_id':param._id},function(erro,resu){

	    		  if (erro)  
	    		    {  
	    		    	var error = new Error();
	    		    	error.number= consts.Error.ERROR_GENERAL;
	    		    	error.message=consts.Message.UNKNOWN;
	    		    	
	    		        console.log(erro);
	    		        if(callback){
	    		        	callback(error,null);
	    		        }
	    		        
		    	    	db.close();

	    		        return;
	    		    }  
	    		
	    	     	var colnote = db.collection("tournote");
	    	     	console.log(-resu.result.n);

	    		    colnote.findAndModify({'_id':param.contID},[],{$inc:{'commentedNum':-resu.result.n}},{'new':true,upsert:false},function(e,obj){
	    		    	if(e){
	    		    		error = new Error();
		    		    	error.number= consts.Error.ERROR_GENERAL;
		    		    	error.message=consts.Message.UNKNOWN;
		    		    	
		    		        console.log(e);
		    		        if(callback){
		    		        	callback(error,null);
		    		        }
		    		        
			    	    	db.close();

		    		        return;
	    		    	}else{
	    		    		var content = {};
	    		    		content.commentedNum= obj.value.commentedNum;
	    	    	    	db.close();

	    		    		callback(null, content);
	    		    	}
	    		    });
	    		
	    	});
	    	

	    	
	    }  
	});  
	
}

/*
 * 内部函数添加评论
 */
function upsertCommentInner(comment,user,db,callback){

	getNextComment_Value(db,function(err,obj){
	    		
	    		if(err){
	    			
	    			var error = new Error();
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	        if(callback){
	    	        	callback(error,null);
	    	        }
	    	        db.close();
	    			return;
	    		}
	    		console.log(obj);

	    		comment._id=obj.value.tournote_comment_value;
		        var t=Date.now();
		               
		        comment.userID=user.userID;
		        comment.createTime = t;
		        comment.baseLine=obj.value.timeline_value;
		        console.log('aaaaaaaaaa');
		    	var col = db.collection("tournote_comment"); 
		    	
		    	col.save(comment,[],function(errr,data){
	    		if(errr){
	    			var error = new Error();
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	    	console.log(errr);
	    		    if(callback){
	    		        	callback(error,null);
	    		    }
	    		    
	    	        db.close();

	    		    return;
	    		}
	    		
	    		var tuser= {};
	    		tuser._id=user.userID;
	    		tuser.userID=user.userID;
	    		tuser.iconURL=user.iconURL;
	    		tuser.nickName = user.nickName;
	    		
	    		tournote_user.insert(tuser,db,null);
	    		
		    	var colnote = db.collection("tournote"); 
		    	var whereStr ={'_id':comment.contID};

			    	colnote.findAndModify(whereStr,[],{$inc:{'commentedNum':1},$set:{'baseLine':obj.value.timeline_value}},{'new':true,upsert:false},function(e,ob){
	    		    	if(e){
	    		    		error = new Error();
		    		    	error.number= consts.Error.ERROR_GENERAL;
		    		    	error.message=consts.Message.UNKNOWN;
		    		    	
		    		        console.log(e);
		    		        if(callback){
		    		        	callback(error,null);
		    		        }
			    	        db.close();

		    		        return;
	    		    	}else{
	    		    		console.log(JSON.stringify(ob));
	    		    		var content = {};
	    		    		content.commentedNum= ob.value.commentedNum;
	    	    	        db.close();

	    		    		callback(null, content);
	    		    	}
	    		    });
		    
		    	});
		    	
	});
	   
	
	
}

module.exports = {
		insert:insert,
		listCommentCommand:listCommentCommand,
		listComment:listComment,
		batchComments:batchComments,
		listCommenttoData:listCommenttoData,
		praise:praise,
		commentDel:commentDel,
	};

